<template>
  <div class="ele-login">
    <div><h1>App</h1></div>
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules">
      <el-form-item prop="username"><el-input
        ref="username"
        v-model="loginForm.username"
        placeholder="User name"
        tabindex="1"
        clearable
        prefix-icon="el-icon-user-solid"
        @keyup.enter.native="enterOnUserName"
      /></el-form-item>
      <el-form-item prop="password"><el-input
        ref="password"
        v-model="loginForm.password"
        placeholder="Pass word"
        :type="passType"
        tabindex="2"
        clearable
        prefix-icon="el-icon-lock"
        @keyup.enter.native="loginByUserName"
      /></el-form-item>
      <el-form-item prop="loginButton"><el-button
        ref="loginButton"
        type="primary"
        tabindex="3"
        round
        :loading="logging"
        @click.native.prevent="loginByUserName"
      >登录</el-button></el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    const showLoginInfo = (rule, value, callback) => {
      if (this.loginInfo) {
        callback(new Error(this.loginInfo))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: 'admin',
        password: '111111'
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: '请输入用户名' }],
        password: [{ required: true, trigger: 'blur', min: 6,
          message: '密码不少于6个字符' }],
        loginButton: [{ validator: showLoginInfo }]
      },
      logging: false,
      passType: 'password',
      redirect: undefined,
      loginInfo: undefined
    }
  },
  methods: {
    enterOnUserName() {
      this.$refs.password.focus()
    },
    loginByUserName() {
      this.loginInfo = undefined
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.logging = true
          this.$store.dispatch('user/loginByUserName', this.loginForm)
            .then(() => {
              this.logging = false
              this.$router.push({ path: this.redirect || '/' })
            }).catch(err => {
              this.loginInfo = err
              this.$refs['loginForm'].validateField('loginButton')
              this.logging = false
            })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.ele-login {
  margin: 2rem auto;
  padding: 0 2rem;
  max-width: 24rem;
  text-align: center;
  h1 {
    margin: 8rem auto 2rem;
  }
  .el-button {
    margin: 1rem auto;
    width: 100%;
  }
  .el-input__prefix {
    width: 2rem;
    font-size: 2rem;
  }
  .el-input__inner {
    padding-left: 3rem;
  }
}
</style>

